package com.ykl.cas.controller;

import com.alibaba.fastjson.JSONObject;
import com.ykl.cas.utils.DataSourceUtils;
import com.ykl.cas.utils.JSONUtils;
import com.ykl.cas.utils.SecurityUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;

@Controller
public class UserController {

  @PostMapping("/registerUser")
  @ResponseBody
  public String registerUser(@RequestBody String registerInfo) throws UnsupportedEncodingException {
    // 创建JDBC模板
    JdbcTemplate jdbcTemplate = new JdbcTemplate();
    jdbcTemplate.setDataSource(DataSourceUtils.getDataSource());
    //将受到的字符串转化
    String usernameAndPasswordUTF8 = URLDecoder.decode(registerInfo, "UTF-8");
    String usernameAndPasswordStr = usernameAndPasswordUTF8.substring(0, usernameAndPasswordUTF8.length() - 1);
    HashMap map = JSONObject.parseObject(usernameAndPasswordStr, HashMap.class);
    String registerPassword = map.get("registerPassword").toString();
    String registerUsername = map.get("registerUsername").toString();
    String nickName = map.get("nickName").toString();
//要返回的信息
    String msg = "";

//
    String querySql = "select count(*) from sys_user where user_name = ?";
    int queryUsernameNum = jdbcTemplate.queryForObject(querySql, int.class, map.get("registerUsername"));
    //判断密码位数
    if (registerPassword.length() < 6 || registerPassword.length() > 19) {
      msg = "密码必须是6-20个字符之间";
      return JSONUtils.responseMsg(msg);
    }
    //查看用户是否存在
    if (queryUsernameNum > 0) {
      msg = "该用户已存在";
      return JSONUtils.responseMsg(msg);
    }
    //对密码进行加密
    String securityPassword= SecurityUtils.encryptPassword(registerPassword);
    Date date = new Date(System.currentTimeMillis());

    String insertUserSql = "INSERT INTO sys_user (dept_id,user_name,password,nick_name,create_by,create_time) VALUES('102',?,?,?,?,?)";
    int num = jdbcTemplate.update(insertUserSql,registerUsername,securityPassword,nickName,registerUsername,date);
    //判断是否注册成功
    if (num > 0) {
      msg = "注册成功,可以登陆了！";
      return JSONUtils.responseMsg(msg);
    }
    msg = "注册失败";
    return JSONUtils.responseMsg(msg);
  }
}
